package com.starbaba.loanActivity.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.activityCommend.model.LoanAdvertModel;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.loanActivity.model.ContentActivityModel;
import com.starbaba.loanActivity.model.LoanProductModel;
import com.starbaba.loanActivity.model.UserCommentModel;
import com.starbaba.loanActivity.service.LoanProductService;
import com.starbaba.loantopic.model.LoanTopicModel;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.dictionary.IStatus;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.redis.JedisUtils;
import com.tuanzi.server.loan_base.constant.LoanConstant;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import com.tuanzi.server.loan_base.model.db.LoanProductInfo;

@SuppressWarnings({ "serial", "unchecked", "rawtypes", "unused" })
public class LoanProductAction extends BaseAction implements ModelDriven<LoanProductModel> {

	@SuppressWarnings("deprecation")
	final BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	private LoanProductModel model;

	private LoanProductService service;

	private ArrayList<ControlLogCategory> logCategorysArrayList;

	private static final String COMM_REDIS_KEY = "loan:activity_comment_list_"; // 评论列表在redis中key的前缀，跟loan_service中的获取活动评论列表要保持一致

	@Autowired
	@Qualifier("loanProductServiceImpl")
	public void setService(LoanProductService service) {
		this.service = service;
	}

	@Override
	public LoanProductModel getModel() {
		if (model == null) {
			model = new LoanProductModel();
		}
		return model;
	}

	public String show() {
		return SUCCESS;
	}

	public String editComment() throws AppException {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String activityId = (String) paramsMap.get("activityId");

		String commSql = "SELECT * FROM loan_user_comment c WHERE c.activity_id = ? AND c.comment_type = 2 ";
		List<UserCommentModel> commList = dao.list(commSql, UserCommentModel.class, activityId);
		paramsMap.put("commList", commList);

		String commCountSql = "SELECT count(1) FROM loan_user_comment c WHERE c.activity_id = ? AND c.comment_type = 2";
		Integer count = dao.getInt(commCountSql, activityId);
		paramsMap.put("commCount", count);
		paramsMap.put("activityId", activityId);

		return "success";
	}

	public void saveComments() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String activityId = (String) paramsMap.get("activityId");
		JsonObject object = new JsonObject();
		try {
			batchSaveComment(paramsMap, activityId);
			object.addProperty("success", 1);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 活动列表
	 */
	public void getActivityList() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();

		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		List list = service.getDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());

		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}

		List<ContentActivityModel> listtemp = getModelList();
		paramsMap.put("modelList", listtemp);

	}

	public String getInfo() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		String id = (String) paramsMap.get("id");

		LoanProductModel vo = new LoanProductModel();
		try {
			if (id != null)
				model = dao.get("select * from loan_product_info where id =?", LoanProductModel.class, id);

			if (model == null) {
				model = new LoanProductModel();
			}

			paramsMap.put("model", model);
		} catch (AppException e) {
			e.printStackTrace();
		}

		List<ContentActivityModel> list = getModelList();
		paramsMap.put("modelList", list);
		return SUCCESS;
	}

	/**
	 * 模板列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<ContentActivityModel> getModelList() {

		String sql = "select id,name from loan_content_activity";
		try {
			List<ContentActivityModel> list = dao.list(sql, ContentActivityModel.class, new Object[] {});

			return list;
		} catch (AppException e) {

			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 编辑活动
	 * 
	 * @return
	 * @throws Exception
	 */
	public String editActivity() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		String id = (String) paramsMap.get("id");
		if (!StringUtils.isEmpty(id)) {
			LoanProductModel vo = new LoanProductModel();
			try {
				model = dao.get("select * from loan_product_info where id =?", LoanProductModel.class, id);
				String type = model.getType();
				if (!StringUtils.isEmpty(type)) {
					JsonObject result = JSONUtils.toJsonObject(type);
					JsonElement identity = result.get("identity");
					if (null != identity) {
						String identity_type = "";
						JsonArray indentity_array = result.get("identity").getAsJsonArray();
						for (int i = 0; i < indentity_array.size(); i++) {
							if (StringUtils.isEmpty(identity_type)) {
								identity_type += indentity_array.get(i).getAsString();
							} else {
								identity_type += "," + indentity_array.get(i).getAsString();
							}
						}
						model.setIdentity_type(identity_type);
					}

					JsonElement cash_loan = result.get("cash_loan");
					if (null != cash_loan) {
						String cash_loan_type = "";
						JsonArray cash_loan_array = cash_loan.getAsJsonArray();
						for (int i = 0; i < cash_loan_array.size(); i++) {
							if (StringUtils.isEmpty(cash_loan_type)) {
								cash_loan_type += cash_loan_array.get(i).getAsString();
							} else {
								cash_loan_type += "," + cash_loan_array.get(i).getAsString();
							}
						}
						model.setCash_loan_type(cash_loan_type);
					}
					JsonElement credit = result.get("credit");
					if (null != credit) {
						String credit_type = "";
						JsonArray credit_array = credit.getAsJsonArray();
						for (int i = 0; i < credit_array.size(); i++) {
							if (StringUtils.isEmpty(credit_type)) {
								credit_type += credit_array.get(i).getAsString();
							} else {
								credit_type += "," + credit_array.get(i).getAsString();
							}
						}
						model.setCredit_type(credit_type);
					}
				}
				paramsMap.put("model", model);

			} catch (AppException e) {
				e.printStackTrace();
			}
		}
		List<ContentActivityModel> list = getModelList();
		paramsMap.put("modelList", list);
		return SUCCESS;
	}

	/**
	 * 新增/编辑产品
	 * 
	 * @throws ParseException
	 * @throws IOException
	 */
	public void saveActivity() throws ParseException, IOException {
		boolean isValidate = true;
		ResultJson resultJs = new ResultJson();
		JsonObject result = new JsonObject();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String currDate = format.format(new Date());
		/*
		 * if(!StringUtils.isEmpty(startTime)){ if (compareDate(startTime,
		 * currDate) == -1){ isValidate = false; resultJs.msg = "上线时间不能小于当前时间";
		 * } } if(StringUtils.isEmpty(startTime) &&
		 * !StringUtils.isEmpty(endTime)){ if (compareDate(endTime, currDate) ==
		 * -1){ isValidate = false; resultJs.msg = "下线时间不能小于当前时间"; } }
		 * if(!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)){
		 * if (compareDate(startTime, endTime) == 1){ isValidate = false;
		 * resultJs.msg = "下线时间不能小于上线时间"; } }
		 */

		if (isValidate) {
			if (StringUtils.isEmpty(id)) { // 新增
				SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String date = tempFormat.format(new Date());
				model.setCtime(date);
				Long activityId = service.save(paramsMap, model);
				resultJs.msg = "保存成功";
			} else {// 更新
				try {
					service.update(paramsMap, model);
					resultJs.msg = "更新成功";
				} catch (Exception e) {
					e.printStackTrace();
					resultJs.msg = "更新失败";
				}
				JedisUtils.del(LoanRedisKey.LOAN_ACTIVITY_INFO + id);
			}
			delRedis();
			delRedis(id);
		}
		try {
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 批量保存评论
	public void batchSaveComment(Map<String, Object> paramsMap, String activityId) throws AppException {
		Integer index = Integer.valueOf((String) paramsMap.get("commentCount"));
		if (index == null || index == 0) {
			return;
		}
		String userId = userVO.getUserid();
		String userName = userVO.getUsername();
		String activityName = model.getName();

		for (int i = 1; i <= index; i++) {
			String commentId = (String) paramsMap.get("commentId" + i); // 评论的主键
			String comment = (String) paramsMap.get("comment" + i);
			String reply = (String) paramsMap.get("reply" + i);
			String commentTime = (String) paramsMap.get("commentTime" + i);
			String effective = (String) paramsMap.get("effective" + i);
			String score = (String) paramsMap.get("score" + i);
			if (StringUtils.isEmpty(comment)) {
				continue;
			}
			if (StringUtils.isEmpty(commentTime)) {
				SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				commentTime = tempFormat.format(new Date());
			}
			if (StringUtils.isEmpty(effective)) {
				effective = "0";
			}
			if (StringUtils.isEmpty(score)) {
				score = "0";
			}
			if (StringUtils.isEmpty(commentId)) { // 新增
				UserCommentModel model = new UserCommentModel();
				model.setActivity_id(Long.valueOf(activityId));
				model.setComment_type(2);
				model.setComment(comment);
				model.setReply(reply);
				model.setCreate_time(commentTime);
				model.setCreate_date(commentTime);
				model.setEffective(Long.valueOf(effective));
				model.setScore(Integer.valueOf(score));
				model.setUpdate_time(new Date());
				model.setUser_id(userId);
				model.setUser_name(userName);
				try {
					dao.add(model);
				} catch (AppException e) {
					e.printStackTrace();
				}
			} else { // 更新
				String updateSql = "UPDATE loan_user_comment SET score= ?,comment= ?,create_time= ?,effective= ?,reply= ?,update_time = ? WHERE id = ?";
				try {
					dao.update(updateSql, new Object[] { score, comment, commentTime, effective, reply, new Date(),
							commentId });
				} catch (AppException e) {
					e.printStackTrace();
				}
			}
		}
		deleteCommInRedis(null, model.getId() + "");
	}

	public void deleteComment() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String commId = (String) paramsMap.get("commentId");
		String deleteSql = "DELETE FROM loan_user_comment WHERE id = ?";
		String selectSql = "SELECT * FROM loan_user_comment c WHERE c.id = ?";
		try {
			UserCommentModel comm = dao.get(selectSql, UserCommentModel.class, commId);
			String activityId = comm.getActivity_id() + "";

			dao.delete(deleteSql, new Object[] { commId });
			deleteCommInRedis(commId, activityId);
		} catch (AppException e) {
			e.printStackTrace();
		}
	}

	// 删除缓存
	public void deleteCommInRedis(String commentId, String activityId) throws AppException {
		if (activityId == null || "".equals(activityId)) { // 如果活动id为空，需要获取活动id
			String selectSql = "SELECT * FROM loan_user_comment c WHERE c.id = ?";
			UserCommentModel comm = dao.get(selectSql, UserCommentModel.class, commentId);
			if (comm == null) {
				return;
			}
			activityId = comm.getActivity_id() + "";
		}
		String redisKey = COMM_REDIS_KEY + activityId;
		JedisUtils.del(redisKey);
	}

	/**
	 * 产品上线/下线
	 * 
	 * @throws NumberFormatException
	 * @throws AppException
	 */
	public void updateStatus() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String status = (String) paramsMap.get("status");
		try {
			String sql = "update loan_product_info c set c.status = ? where c.id= ? ";
			dao.update(sql, status, Long.parseLong(id));
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "操作成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
			delRedis();
			delRedis(id);
			if("0".equals(status)) {
				LoanAdvertModel advert = new LoanAdvertModel();
				advert.setActivity_id(Integer.valueOf(id));
				advert.setStatus(0);
				advert.setUtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				dao.update(advert, "activity_id");
			}
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void sortTab() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String prdidListStr = (String) paramsMap.get("prdSortList");
		String[] prdidList = prdidListStr.split("#");
		parsePageRequest();
		try {
			String sql = "update loan_product_info c set c.position = ? where c.id = ?";
			for (int index = 0; index < prdidList.length; ++index) {
				Long id = Long.parseLong(prdidList[index]);
				dao.update(sql, index, id);
				delRedis();
				delRedis(String.valueOf(id));
			}
			responseSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			responseError(e);
		}
	}

	/**
	 * 排序
	 */
	public void sortPosition() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String valueindex = (String) paramsMap.get("valueindex");
		String ids = (String) paramsMap.get("ids");
		String[] idvalue = ids.split(",");
		String[] indexs = valueindex.split(",");
		parsePageRequest();
		try {
			String sql = "update loan_product_info c set c.position = ? where c.id = ?";
			for (int i = 0; i < indexs.length; i++) {
				Long id = Long.parseLong(idvalue[i]);
				int index = Integer.parseInt(indexs[i]);
				dao.update(sql, index, id);
				delRedis();
				delRedis(String.valueOf(id));
			}
			responseSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			responseError(e);
		}
	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description <p>
	 *              返回错误信息
	 *              </p>
	 *              　　　　　
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	private void loadLogCategory(String id, String name) {
		logCategorysArrayList.clear();
		ControlLogCategory logCategory = new ControlLogCategory();
		logCategory.setId(id);
		logCategory.setName(name);
		logCategorysArrayList.add(logCategory);
	}

	@Override
	public ArrayList<ControlLogCategory> getProduct() {
		return logCategorysArrayList;
	}

	public static void delRedis() {
		List<String> indexListRedisKey = new ArrayList<>(); 
		Integer[] spaceIdArray = LoanConstant.getSpaceIdArray();
		for (Integer spaceId : spaceIdArray) {
			indexListRedisKey.add(LoanRedisKey.LOAN_SPACE_LIST + spaceId);
		}
		JedisUtils.delKeys(indexListRedisKey.toArray(new String[indexListRedisKey.size()]));
		
		try {
			String getTopticIdList = "select id from loan_topic_info where status = ?";
			BaseDao dao = new BaseDao(Constant.POOL_LIFE);
			List<LoanTopicModel> topicList = dao.list(getTopticIdList, LoanTopicModel.class, IStatus.VALIDATE);
			for (LoanTopicModel loanTopicModel : topicList) {
				JedisUtils.delKeys(LoanRedisKey.getTopicRelatedRedisKeys(loanTopicModel.getId()));
			}
			
		} catch (Exception e) {
			LogService.error(e);
		}

		
		if (JedisUtils.exists("loan:activity_list")) {
			JedisUtils.del("loan:activity_list");
		}

		if (JedisUtils.exists("loan:advert_credit_card_list")) {
			JedisUtils.del("loan:advert_credit_card_list");
		}

		if (JedisUtils.exists(LoanRedisKey.LOAN_PROXY_CREDIT_LIST)) {
			JedisUtils.del(LoanRedisKey.LOAN_PROXY_CREDIT_LIST);
		}
	}

	public static void delRedis(String id) {

		if (JedisUtils.exists(LoanRedisKey.LOAN_ACTIVITY_INFO + id)) {
			JedisUtils.del(LoanRedisKey.LOAN_ACTIVITY_INFO + id);
		}

		if (JedisUtils.exists(LoanRedisKey.LOAN_ONLINE_ACTIVITY_INFO + id)) {
			JedisUtils.del(LoanRedisKey.LOAN_ONLINE_ACTIVITY_INFO + id);
		}

		if (JedisUtils.exists(LoanRedisKey.LOAN_DETAIL_ACTIVITY_ID + id)) {
			JedisUtils.del(LoanRedisKey.LOAN_DETAIL_ACTIVITY_ID + id);
		}
	}

	public void delRedisMethod() {
		delRedis();
		responseSuccess();
	}

	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * public void updatePosition() throws AppException{ paramsMap =
	 * PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(),
	 * paramsMap); String id = (String) paramsMap.get("id"); String position =
	 * (String) paramsMap.get("position"); String sql =
	 * "update loan_product_info set position= ? where id = ?"; dao.update(sql,
	 * new Object[]{position,id}); responseSuccess(); }
	 */

	/**
	 * 修改位置
	 */
	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void updatePosition() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String position = (String) paramsMap.get("position");

		String sql = "update loan_product_info set position = ? where id = ?";

		try {
			if (position != null && position != "") {
				dao.update(sql, new Object[] { Integer.parseInt(position), id });
			} else {
				dao.update(sql, new Object[] { Integer.parseInt(position), id });
			}

			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "修改成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showInvest() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String str = (String) paramsMap.get("ids");
		String status = (String) paramsMap.get("status");
		String[] ids = str.split(",");
		String sql = "update loan_product_info set status = ? where id =?";
		for (String id : ids) {
			if (!StringUtils.isEmpty(id)) {
				try {
					dao.update(sql, new Object[] { status, id });
				} catch (AppException e) {
					e.printStackTrace();
				}
			}
		}
		responseSuccess();
	}

	/**
	 * 时间比较
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 */
	public static int compareDate(String date1, String date2) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(format.parse(date1));
		Date d1 = calendar.getTime();
		calendar.setTime(format.parse(date2));
		Date d2 = calendar.getTime();
		return d1.compareTo(d2); // d1 < d2 返回 -1 , d1 > d2 返回 1 , d1 = d2 返回 0
	}

	public String uploadToQiniu(File srcFile) {
		String iconUrl = null;
		if (srcFile.isDirectory()) {
			return iconUrl;
		} else {
			try {
				FileInputStream in = new FileInputStream(srcFile);
				// Zone为七牛机房所在地，根据源所在机房配置
				Configuration config = new Configuration(Zone.zone0());
				iconUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return iconUrl;
	}

	/**
	 * 查询所有产品
	 */
	public void getAllLoanList() {
		PageResponse pageResponse = new PageResponse();
		List list = service.getAllList(pageResponse);
		pageResponse.setAaData(list);
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
